#include "http.h"
#include "check.h"
#include "WebSocketServer.h"
#include <iostream>
#include <thread>
#include <csignal>
#include <atomic>

// 全局WebSocket服务器
WebSocketServer* ws_server = nullptr;
std::thread log_processor;

void cleanup(int signal) {
    log_thread_running = false;
    queue_cv.notify_one();
    
    if (log_processor.joinable()) {
        log_processor.join();
    }
    
    if (ws_server) {
        ws_server->stop();
        delete ws_server;
        ws_server = nullptr;
    }
    
    exit(signal);
}

int main() {
    // 注册信号处理
    signal(SIGINT, cleanup);
    signal(SIGTERM, cleanup);
    
    try {
        // 创建WebSocket服务器 (端口8081)
        ws_server = new WebSocketServer(8081);
        ws_server->start();
        
        // 启动日志处理线程
        log_thread_running = true;
        log_processor = std::thread(log_processor_thread, ws_server);
        
        // 启动HTTP服务器 (端口8080)
        start_http_server(8080);
        
        std::cout << "Started HTTP server and WebSocket log server" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        cleanup(1);
    }
    
    return 0;
}